<?php
namespace app\modules\frontend\models;

use Yii;

class VueRouter extends \yii\db\ActiveRecord
{  
    public static function tableName()
    {
        return '{{%vue_router}}';
    }

    public function rules()
    {
        return [
            ['navid', 'integer', 'message' => 'navid必须为数字，或数字字符串', 
                                  'min'=>0, 'tooSmall' => 'navid最小存储0', 
                                  'max'=>65535, 'tooBig' => 'navid最大存储65535'],
            // ['path', 'required', 'message' => 'path不能为空'],
            ['path', 'default', 'value' => ''],
            ['path', 'string', 'message' => 'path必须是字符串',
                               'min' => 2, 'tooShort' => 'path最短2位',
                               'max' => 64, 'tooLong' => 'path最长64位'],
            // ['name', 'required', 'message' => 'name不能为空'],
            ['name', 'default', 'value' => ''],
            ['name', 'string', 'message' => 'name必须是字符串',
                               'min' => 2, 'tooShort' => 'name最短2位',
                               'max' => 64, 'tooLong' => 'name最长64位'],
            // ['component', 'required', 'message' => 'component不能为空'],
            ['component', 'default', 'value' => ''],
            ['component', 'string', 'message' => 'component必须是字符串',
                                    'min' => 2, 'tooShort' => 'component最短2位',
                                    'max' => 64, 'tooLong' => 'component最长64位'],
        ];
    }


    /*
    添加路由
    $navid     menu表主键
    */
    public function addRouter($data, $navid)
    {
        // P($data);
        $vueRouter = VueRouter::find()->where('navid = :id', [':id' => $navid])->one();
        if(is_null($vueRouter)){//当前没有此菜单的路由
            //添加路由
            $data['VueRouter']['navid'] = $navid;
            if($this->load($data) and $this->validate()){
                if($this->save(false)){
                    return true;
                }
            }
        }else{//当前有此菜单的路由
            //修改路由
            if($this->load($data) and $this->validate()){
                if(!empty($this->navid)){
                    $vueRouter->navid = $this->navid;
                }
                if(!empty($this->path)){
                    $vueRouter->path = $this->path;
                }
                if(!empty($this->name)){
                    $vueRouter->name = $this->name;
                }
                if(!empty($this->component)){
                    $vueRouter->component = $this->component;
                }
                // P($vueRouter);
                if($vueRouter->save(false)){
                    return true;
                }
            }
        }
        return false;
    }
    
}